package com.yjc.hire.utils;


import com.yjc.hire.exceptions.GraceException;
import com.yjc.hire.grace.result.ResponseStatusEnum;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.Date;

@Slf4j
@Component
public class JWTUtils {
    @Autowired
    private jwtProperties jwtProperties;


    public static  String at = "@";

    public String createJWtWithPrefix(String body,Long expiresTime,String prefix){
        if (expiresTime == null)
            GraceException.disPlay(ResponseStatusEnum.SYSTEM_NO_EXPIRE_ERROR);
        return prefix + at + createJWt(body,expiresTime);
    }

    public String createJWtWithPrefix(String body,String prefix){
        return prefix + at + createJWt(body);
    }
    public String createJWt(String body){
        return dealJWT(body,null);
    }
    public String createJWt(String body,Long expireTime){
        if (expireTime == null)
            GraceException.disPlay(ResponseStatusEnum.SYSTEM_NO_EXPIRE_ERROR);
        return dealJWT(body,expireTime);
    }

    public String dealJWT(String body,Long expireTime){
        String userKey = jwtProperties.getKey();
        String base64 = Arrays.toString(new Base64().encode(userKey.getBytes()));
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());
        String jwt = "";
        if (expireTime != null) {
            jwt = generateJwt(body,secretKey,expireTime);
        }
        else {
            jwt = generateJwt(body,secretKey);
        }
        log.info("JWTUtils - dealJwt:" + jwt );
        return jwt;
    }


    public String generateJwt(String body, SecretKey secretKey){
        String jwtToken = Jwts.builder()
                .setSubject(body)
                .signWith(secretKey)
                .compact();
        return jwtToken;
    }

    public String generateJwt(String body, SecretKey secretKey,Long expire){
        Date expireDate = new Date(System.currentTimeMillis()+expire);
        String jwtToken = Jwts.builder()
                .setSubject(body)
                .signWith(secretKey)
                .setExpiration(expireDate)
                .compact();
        return jwtToken;
    }
}
